import { getAdmin } from '@A/resource/admin';
import { formatDate } from '@A/resource/filter'
/**
 * 判断是否为数字类类型
 * @param value
 * @returns {boolean}
 */
export const isNumber = (value) => {
  let paten = /^(-)?\d+(\.\d+)?$/;
  if (paten.exec(value) === null || value === "") {
    return false
  } else {
    return true
  }
};
/**
 * 上传失败后后端返回Excel文件地址，前端进行下载
 * 异常下载，可适用导出(试用axios请求)
 * @param fullName  (异常文件内容名称)
 * @param url   (后端返回的异常url地址)
 * 例如：url: http://wokezhineng.oss-cn-huhehaote.aliyuncs.com/image/20191107/96d560ee-ac44-4555-9bd1-e04949c8bb96.xls
 */
export const exceptionDownload  = ( fullName, url ) => {
  let eLink = document.createElement('a');
  eLink.download = fullName;
  eLink.style.display = 'none';
  eLink.href = url;
  document.body.appendChild(eLink);
  eLink.click();
  document.body.removeChild(eLink);
};
/**
 * 后端返回文件流的格式进行导出，
 * 注：如果后端返回http路径，试用上面的进行下载
 * 如果选择一下方式进行导出，axios请求的responseType：'blob'
 * @param content
 * @param name
 */
export const urlExport = ( content, name ) => {
  let blob = new Blob([content]);
  let fileName = name + formatDate(new Date(), 1) + '.xls';
  if ('download' in document.createElement('a')) { // 非IE下载
    const eLink = document.createElement('a');
    eLink.download = fileName;
    eLink.style.display = 'none';
    eLink.href = URL.createObjectURL(blob);
    document.body.appendChild(eLink);
    eLink.click();
    URL.revokeObjectURL(eLink.href);// 释放URL 对象
    document.body.removeChild(eLink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
};
/**
 * fetch请求返回数据的处理（后端返回文件流）
 * @param data
 * @param name
 */
export const fetchExport = ( data, name ) => {
  data.blob().then(content => {
    let eLink = document.createElement('a');
    eLink.download = name;
    eLink.style.display = 'none';
    let blob = new Blob([content]);
    eLink.href = URL.createObjectURL(blob);
    document.body.appendChild(eLink);
    eLink.click();
    document.body.removeChild(eLink);
  })
};
/**
 * 节制函数
 * 节流： 使连续执行的事件或函数，变为固定时间间隔执行
 */
export const control = (fn, delay) => {
  let timer;
  return function () {
    let _this = this;
    let args = arguments;
    if (timer) {
      return;
    }
    timer = setTimeout(function () {
      fn.apply(_this, args);
      timer = null;
    }, delay)
  }
};
/**
 * 获取url路径的参数
 * name为要获取的参数名
 * @param name
 * @returns {string|null}
 */
export const getUrlParam = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let rrr = decodeURIComponent(window.location.search);
  let r = rrr.substr(1).match(reg);
  if(r != null) return unescape(r[2]);
  return null;
};
/**
 * 手机号中间四位*代替
 * @param phone
 * @returns {*}
 */
export const handlePhone = (phone) => {
  return phone.replace(phone.substring(3,7), "****")
};
/**
 * 合并表格单元格
 * @param list
 * @returns {*}
 */
export const handleTable = (list) => {
  for (let key in list[0]) {
    let k = 0;
    while (k < list.length) {
      list[k][key + 'count'] = 1;
      list[k][key + 'show'] = true;
      for (var i = k + 1; i <= list.length - 1; i++) {
        if (list[k][key] === list[i][key] && list[k][key] !== '') {
          if (list[i].unit_id === list[k].unit_id) {
            list[k][key + 'count']++;
            list[k][key + 'show'] = true;
          } else {
            list[i][key + 'count'] = 1;
            list[i][key + 'show'] = true;
          }
        } else {
          break;
        }
      }
      k = i;
    }
  }
  return list
};
/**
 * 清空对象值
 * @param obj
 */
export const emptyObject = ( obj ) => {
  for ( let key in obj ) {
    if (!Array.isArray(obj[key])) {
      obj[key] = ''
    } else {
      obj[key] = []
    }
  }
};
/**
 * 删除数组
 * @param Array
 * @param val
 * @returns {*}
 */
export const emptyArray = (arr, val) => {
  if (Array.isArray(arr)) {
    return arr.filter( (item) => {
      if (Object.prototype.toString.call(item) === "[object Object]") {
        let value = '';
        for ( let key in item ) {
          if (!Array.isArray(item[key])) {
            if (item[key] === val) {
              value = item[key]
            }
          }
        }
        return value != val
      } else {
        return item != val
      }
    })
  } else {
    return false
  }
};
/**
 * 对象中相同的值
 * @param newParam
 * @param oldParam
 * @returns {*}
 */
export const valueObject = (newParam, oldParam) => {
  for( let key in newParam) {
    for ( let index in oldParam) {
      if (key === index) {
        oldParam[index] = newParam[key]
      }
    }
  }
  return oldParam
};

export const getFlag = (flag) => {
  if ( getAdmin(sessionStorage, 'admin') === null || getAdmin(sessionStorage, 'admin') === 'null' ) {
    flag = true
  } else {
    flag = false;
    if (getAdmin(sessionStorage, 'admin').companyName) {
      flag = true
    } else {
      if (sessionStorage.getItem('logOut')) {
        flag = true;
      } else {
        flag = false;
      }
    }
  }
  return flag
};
/**
 * 数组数据上移、下移、置顶、置底
 *
 */
export const swapItems =(arr, index1, index2,direction)=>{
  if(direction=='up'){//置顶
    arr.unshift(arr[index1]);
    arr.splice(index1+1,1);
    return arr;
  }
  if(direction=='down'){//置底
    arr.push(arr[index1]);
    arr.splice(index1,1);
    return arr;
  }
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
};
/**
 * 数值限制
 * （限制为整数）
 */

export const numericalRange = ( value,min,max ) => {
  if (value || value ==0) {
    if (value < min) {
      return min;
    }
    if (value > max) {
      return max;
    }
    if (value >= min && value <=max) {
      return parseInt(value)
    }
  }
};
